﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using WeifenLuo.WinFormsUI.Docking;
using DBSourceToolsLib;
using DBConnectionLib;
using DBSourceToolsLib.Composite;

namespace DBSourceTools
{
    public partial class DataForm : MainPanelForm
    {

        private SourceDatabase m_Database;
        private DBSourceToolsLib.SysObjects.SysObject m_SoTableOrView;

        public DataForm(string strDatabase, string strType, string strObject)
            : base( strDatabase, strType, strObject)
        {
            InitializeComponent();
            this.m_Database = UserSettings.Instance().getSourceDatabase(this.m_DatabaseName);
            this.m_SoTableOrView = m_Database.SysObjects.getSysObject("Tables", strObject);
            
            if (this.m_SoTableOrView == null)
                this.m_SoTableOrView = m_Database.SysObjects.getSysObject("Views", strObject);
        }

        private void DataForm_Load(object sender, EventArgs e)
        {
            try
            {
                this.Text = "Data:" + m_Name;
                this.TabText = "Data:" + m_Name;

                this.m_dataGridView1.DataSource = GetData("select * from " + this.m_SoTableOrView.GetFullyQualifiedName());
                this.m_dataGridView1.DataMember = "mydata";
                //this.m_dataGridView1.B
            }
            catch (Exception ex)
            {
                DBSourceToolsLib.SysObjects.UI.Forms.ErrorForm oError =
                    new DBSourceToolsLib.SysObjects.UI.Forms.ErrorForm(ex.ToString());
                oError.Show();

//                MessageBox.Show(ex.ToString());
            }
        }

        private void toolStripButton1_Click(object sender, EventArgs e)
        {
            try
            {
                // Refresh data
                refreshDataToolStripMenuItem_Click(sender, e);
            }
            catch (Exception ex)
            {
                DBSourceToolsLib.SysObjects.UI.Forms.ErrorForm oError =
                    new DBSourceToolsLib.SysObjects.UI.Forms.ErrorForm(ex.ToString());
                oError.Show();
            }
        }

        private void refreshDataToolStripMenuItem_Click(object sender, EventArgs e)
        {
            try
            {
                // Refresh data
                this.m_dataGridView1.DataSource = GetData("select * from " + this.m_SoTableOrView.GetFullyQualifiedName());
                this.m_dataGridView1.DataMember = "mydata";
            }
            catch (Exception ex)
            {
                DBSourceToolsLib.SysObjects.UI.Forms.ErrorForm oError =
                    new DBSourceToolsLib.SysObjects.UI.Forms.ErrorForm(ex.ToString());
                oError.Show();
            }

        }

        private DataSet GetData(string strSelectString)
        {
            this.Cursor = Cursors.WaitCursor;
            
            DataSet oDS = new DataSet();

            using (System.Data.SqlClient.SqlConnection conn = new System.Data.SqlClient.SqlConnection(this.m_Database.ConnectionString))
            {
                conn.Open();
                System.Data.SqlClient.SqlDataAdapter oDA = new System.Data.SqlClient.SqlDataAdapter();
                oDA.SelectCommand = new System.Data.SqlClient.SqlCommand(strSelectString, conn);
                oDA.Fill(oDS, "mydata");
                conn.Close();
            }
            this.Cursor = Cursors.Default;
            return oDS;

        }

        private void m_dataGridView1_DataError(object sender, DataGridViewDataErrorEventArgs e)
        {
            // occurs on data error
        }

        private void toolStripScriptData_Click(object sender, EventArgs e)
        {
            try
            {
                // TODO : COMPLETE 1.2.0.8 ' character in data (kamal101)
                // TODO : COMPLETE 1.2.0.9 show script data window
                this.Cursor = Cursors.WaitCursor;

                DBSourceToolsLib.SourceDatabaseLoader oCompareLoader = new SourceDatabaseLoader(
                    this, DBSourceToolsLib.Commands.DatabaseCommandTypes.NewQuery);

                oCompareLoader.Execute(ref m_Database, "");
                if (oCompareLoader.HasErrors())
                    throw new Exception(oCompareLoader.GetErrorMessage());

                string strNewQueryName = oCompareLoader.NewQueryName;

                DBSourceToolsLib.SysObjects.SysObject oNewQuery =
                    this.m_Database.SysObjects.getSysObject("Queries", strNewQueryName);
                

                string columns = "";
                int iCount = 0;
                foreach (DBSourceToolsLib.SysObjects.ColInfo oColInfo in m_SoTableOrView.Columns)
                {
                    if (iCount > 0)
                        columns += ",";
                    columns += "[" + oColInfo.Name + "]";
                    iCount++;
                }

                string select_string = "select " + columns + " from " + m_SoTableOrView.GetFullyQualifiedName();
                string insert_string = "insert into " + m_SoTableOrView.GetFullyQualifiedName() + " ( " + columns + " ) values ( ";

                StringBuilder oStringBuilder = new StringBuilder();

                oStringBuilder.AppendLine("SET NOCOUNT ON ");
                oStringBuilder.AppendLine("SET IDENTITY_INSERT " + m_SoTableOrView.GetFullyQualifiedName() + " ON ");

                DataTable oDataTable = GetData(select_string).Tables[0];
                foreach (DataRow oRow in oDataTable.Rows)
                {
                    string strLine = insert_string;
                    iCount = 0;
                    foreach (DBSourceToolsLib.SysObjects.ColInfo oColInfo in m_SoTableOrView.Columns)
                    {
                        if (iCount > 0)
                            strLine += ",";
                        iCount++;

                        string strValue;
                        if (oRow.IsNull(oColInfo.Name))
                        {
                            strLine += "null";
                        }
                        else
                        {
                            if (oColInfo.NeedsQuotes())
                                strLine += "'";

                            strValue = oRow[oColInfo.Name].ToString();
                            if (oColInfo.IsBinary())
                                strValue = ((oRow[oColInfo.Name].ToString().CompareTo("True") == 0) ? "1" : "0");
                            if (oColInfo.IsDateTime())
                            {
                                DateTime oTime = DateTime.Parse(oRow[oColInfo.Name].ToString());
                                strValue = oTime.ToString("dd MMM yyyy HH:mm:ss");
                            }

                            string strResultText = "";
                            foreach (char oChar in strValue)
                            {
                                if (oChar == '\'')
                                {
                                    strResultText += "''";
                                }
                                else
                                    strResultText += oChar;
                            }

                            //strValue.Replace("'", "''");
                            strLine += strResultText;
                            if (oColInfo.NeedsQuotes())
                                strLine += "'";
                        }
                        iCount++;
                    }
                    strLine += " ) ";
                    oStringBuilder.AppendLine(strLine);    
                }

                oStringBuilder.AppendLine("SET IDENTITY_INSERT " + m_SoTableOrView.GetFullyQualifiedName() + " OFF ");
                oStringBuilder.AppendLine("SET NOCOUNT OFF ");

                oNewQuery.Text = oStringBuilder.ToString().Replace("\r", "");

                oNewQuery.WriteFile(false, true, null, false);

                WindowList.Instance().ShowWindow(new TreeNodeTag(m_Database.NickName, "File", oCompareLoader.NewQueryFileName, null));

                this.Cursor = Cursors.Default;

                //this.m_Observer.NotifyEvent(m_Database.NickName,
                //        "Queries", strNewQueryName,
                //        DBSourceToolsLib.Interfaces.SourceEditorEvent.FileOpened
                //        , "Generated");
            }
            catch (Exception ex)
            {
                DBSourceToolsLib.SysObjects.UI.Forms.ErrorForm oError =
                    new DBSourceToolsLib.SysObjects.UI.Forms.ErrorForm(ex.ToString());
                oError.ShowDialog(this);

            }

        }
    }
}
